<template>
  <a-modal
    :visible="visible"
    fullscreen
    :footer="false"
    :closable="true"
    unmount-on-close
    :title="mode === 'edit' ? '编辑视图' : '新建视图'"
    @cancel="handleCancel"
    :body-style="{ padding: 0 }"
  >
    <div class="designer-create-page">
      <div class="toolbar">
        <a-space>
          <a-button @click="handleCancel">取消</a-button>
          <a-button type="primary" status="success" @click="saveView"
            >保存</a-button
          >
        </a-space>
      </div>
      <a-tabs v-model:active-key="activeKey" class="designer-tabs">
        <a-tab-pane key="1" title="基本配置">
          <a-form :model="form" layout="vertical" class="base-form">
            <a-form-item field="name" label="视图名称" required>
              <a-input v-model="form.name" placeholder="请输入视图名称" />
            </a-form-item>
            <a-form-item field="desc" label="视图描述">
              <a-input v-model="form.desc" placeholder="请输入视图描述" />
            </a-form-item>
          </a-form>
        </a-tab-pane>
        <a-tab-pane key="2" title="表单设计">
          <div class="designer-form-pane">
            <a-row
              type="flex"
              justify="start"
              :gutter="[0, 0]"
              class="designer-row"
            >
              <a-col :span="4" class="designer-col-left">
                <form-left />
              </a-col>
              <a-col :span="15" class="designer-col-center">
                <form-page />
              </a-col>
              <a-col :span="5" class="designer-col-right">
                <form-right />
              </a-col>
            </a-row>
          </div>
        </a-tab-pane>
      </a-tabs>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { reactive, provide } from "vue";
import { Message } from "@arco-design/web-vue";
import { buildCreateViewDto, createView } from "@/api/views";
import FormLeft from "@/components/Form/FormLeft.vue";
import FormPage from "@/components/Form/FormPage.vue";
import FormRight from "@/components/Form/FormRight.vue";
const props = defineProps<{
  visible: boolean;
  record?: any;
  mode?: "create" | "edit";
}>();
const emits = defineEmits(["update:visible", "success"]);
const form = reactive({ name: "", desc: "" });

// 为三栏设计器组件提供注入数据对象
const dataObj = reactive({
  pageData: [],
  allFormConfig: {
    labelWidth: 120,
    labelAlign: "left",
    isMobile: false,
    modalWidth: 800,
    modalHeight: 700,
  },
  selectIndex: undefined as undefined | number,
  // 由中心画布 `FormPage.vue` 的 handleSave() 写入的 JSON 字符串
  viewUi: "",
});
provide("dataObj", dataObj);

function handleCancel() {
  emits("update:visible", false);
}

async function saveView() {
  try {
    if (!form.name) {
      Message.warning("请输入视图名称");
      return;
    }
    const dto = buildCreateViewDto({
      viewName: form.name,
      viewDesc: form.desc,
      viewType: "view", // 默认视图类型，如需按业务传入 'process'|'task' 请告知
      pageData: dataObj.pageData,
      allFormConfig: dataObj.allFormConfig,
    });
    // 始终以当前画布数据生成最新 viewUi（避免使用初次回显的旧值）
    const playload = { processViewAddDTO: dto };
    await createView(playload);
    Message.success("保存成功");
    emits("success");
    emits("update:visible", false);
  } catch (e: any) {
    console.error(e);
    Message.error(e?.message || "保存失败");
  }
}

// 预填充：当进入编辑模式且有 record 时，从 record 填充 name/desc，并解析 viewUi 渲染画布
import { watch, nextTick, ref, onMounted } from "vue";
const activeKey = ref("1");

function applyRecord(rec: any) {
  try {
    console.log("[DesignerCreate] applyRecord ->", rec);
    form.name = rec?.viewName ?? rec?.name ?? "";
    form.desc = rec?.viewDesc ?? rec?.desc ?? "";
    const ui = rec?.viewUi;
    if (ui) {
      const parsed = typeof ui === "string" ? JSON.parse(ui) : ui;
      // 等待内部 FormPage 等完成挂载后再写入，避免首次渲染错过响应
      nextTick(() => {
        console.log("[DesignerCreate] parsed viewUi ->", parsed);
        if (Array.isArray(parsed?.pageData)) {
          // 保持同一数组引用，提升下游依赖的响应性
          (dataObj.pageData as any[]).splice(
            0,
            (dataObj.pageData as any[]).length,
            ...parsed.pageData
          );
          // 默认选中第一个，便于感知加载结果
          dataObj.selectIndex =
            (dataObj.pageData as any[]).length > 0 ? 0 : undefined;
        }
        if (parsed?.allFormConfig && typeof parsed.allFormConfig === "object") {
          Object.assign(dataObj.allFormConfig as any, parsed.allFormConfig);
        }
        dataObj.viewUi = typeof ui === "string" ? ui : JSON.stringify(ui);
      });
    } else {
      // 无 viewUi 时，保持空白画布
      (dataObj.pageData as any[]).splice(0, (dataObj.pageData as any[]).length);
      dataObj.viewUi = "";
    }
  } catch (err) {
    console.error("解析 viewUi 失败", err);
  }
}

function resetState() {
  form.name = "";
  form.desc = "";
  (dataObj.pageData as any[]).splice(0, (dataObj.pageData as any[]).length);
  dataObj.selectIndex = undefined;
  dataObj.viewUi = "";
}

watch(
  () => props.visible,
  (v) => {
    if (v) {
      if (props.mode === "edit" && props.record) {
        activeKey.value = "2";
        nextTick(() => {
          console.log("[DesignerCreate] visible:true mode=edit -> apply");
          applyRecord(props.record as any);
        });
      } else {
        activeKey.value = "1";
        resetState();
      }
    }
  }
);

// 当记录在可见状态下发生变化时，重新应用（配合父组件 :key 降低概率，但此处兜底）
watch(
  () => props.record,
  (rec) => {
    if (props.visible && props.mode === "edit" && rec) {
      activeKey.value = "2";
      applyRecord(rec);
    }
  }
);

function tryApply() {
  if (props.visible && props.mode === "edit" && props.record) {
    activeKey.value = "2";
    nextTick(() => applyRecord(props.record as any));
  }
}

onMounted(() => {
  // 初次挂载时，若已处于可见编辑状态，立即尝试回填
  tryApply();
});
</script>

<style scoped>
.designer-create-page {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #f6f7fb;
}
.toolbar {
  background: #fff;
  padding: 12px 16px;
  display: flex;
  justify-content: flex-end;
  border-bottom: 1px solid #f0f0f0;
}
.base-form {
  background: #fff;
  padding: 24px;
  border-radius: 8px;
  margin: 16px;
}
.designer-tabs {
  flex: 1;
  display: flex;
  flex-direction: column;
}
.designer-tabs :deep(.arco-tabs-content) {
  flex: 1;
  display: flex;
}
.designer-form-pane {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 0;
}
.designer-row {
  flex: 1;
  height: 100%;
  margin: 0;
}
.designer-col-left,
.designer-col-center,
.designer-col-right {
  height: calc(100vh - 100px);
  /* 预留页签和头部空间，必要时调整 */
  overflow: auto;
}
</style>
